#    Rubatom
#    Copyright (c) 2014 Sebastian Dufner
#
#    This file is part of Rubatom.
#
#    Rubatom is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Rubatom is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

require 'delegate'

require 'rubatom/structure/block'

module Rubatom
  class Template
    class Blocks < SimpleDelegator
      def self.deserialize(input)
        length = input.read_many(4)[0]

        new length.times.map {Block.deserialize(input)}
      end

      def serialize(output)
        output.write_many(size => 4)
        each {|block| block.serialize(output)}
      end
    end

    class Block < ::Rubatom::Structure::Block
      def self.create(id, orientation: 0, hp: 0xff, active: true,
            x: nil, y: nil, z: nil)
        block = Block(x, y, z, 0, 0, 0)
        block.id, block.hp, block.orientation, block.active =
            id, hp, orientation, active
      end

      def self.deserialize(input)
        new(*input.read_many(4, 4, 4, 1, 1, 1))
      end

      def initialize(x, y, z, b1, b2, b3)
        super(b1, b2, b3, version: version)

        @x, @y, @z = x, y, z
      end
      attr_accessor :x, :y, :z

      def serialize(output)
        output.write_many([x, y, z] => [4, 4, 4])
        super(output)
      end
    end

  end
end
